package equipmentBusiness;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by yangxianming on 2018/1/11.
 */
public class OptionExcel {
    String path;

    OptionExcel(String path){
        this.path = path;
    }

    public boolean optionExcel(String filename, HashMap<Integer, ArrayList<String>> hashMap){
        String fileName = path + "data\\equipment\\" + filename;

        FileOutputStream out;
        Workbook wb;
        if (fileName.contains(".xls") && !fileName.contains(".xlsx")){
            wb = new HSSFWorkbook();   //xls
        }else if (fileName.contains(".xlsx")){
            wb = new XSSFWorkbook();   //xlsx
        }else {
            System.out.println("创建文件名需要xls或xlsx");
            return false;
        }
        Sheet sheet = wb.createSheet("设备批量导入");

        int rowMax = 0;
        for (Map.Entry<Integer, ArrayList<String>> me: hashMap.entrySet()){
            int size = me.getValue().size();
            rowMax = (size > rowMax) ? size : rowMax;
        }

        for (int rowIndex = 0; rowIndex < rowMax; rowIndex++){
            Row row = sheet.createRow(rowIndex);
            for (int cellIndex = 0; cellIndex < hashMap.size(); cellIndex++){
                Cell cell = row.createCell(cellIndex);
                try {
                    cell.setCellValue(hashMap.get(cellIndex).get(rowIndex));
                }catch (IndexOutOfBoundsException ioe){
                    cell.setCellValue("");
                }
            }
        }

        try {
            out = new FileOutputStream(fileName);
            wb.write(out);
            out.close();
            return true;
        }catch (Exception e){
            System.out.println(e.getMessage());
            return false;
        }
    }
}
